<template>
  <div>
    <div style="padding-left: 120px; margin-bottom: 30px">
      <el-page-header @back="goBack" content=""></el-page-header>
    </div>
    <div>
      <el-form
        v-loading="isLoading"
        ref="submitForm"
        :rules="rules"
        :model="submitForm"
        label-width="200px"
        class="demo-form-inline"
      >
        <div style="display: flex">
          <div>
            <el-form-item class="commonForm" prop="jName" label="计划名称">
              <el-input
                :disabled="type == 1"
                style="width: 400px"
                placeholder="请输入计划名称"
                v-model="submitForm.jName"
              ></el-input>
            </el-form-item>
            <el-form-item class="commonForm" label="通用性别">
              <el-radio-group :disabled="type == 1" v-model="submitForm.jSex">
                <el-radio :label="1">男</el-radio>
                <el-radio :label="2">女</el-radio>
                <el-radio :label="3">全性别</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item class="commonForm" prop="jScId" label="适用年级">
              <el-select
                :disabled="type == 1"
                clearable
                v-model="submitForm.jScId"
                style="width: 400px"
                v-loading="gradeLoading"
                placeholder="请选择适用年级"
              >
                <el-option
                  v-for="item in gradeSource"
                  :key="item.scId"
                  :value="item.scId"
                  :label="item.scName"
                ></el-option>
              </el-select>
            </el-form-item>
          </div>
          <div>
            <el-form-item class="commonForm" label="计划封面图">
              <el-upload
                style="width: 100%"
                class="upload-demo"
                drag
                :disabled="type == 1"
                v-loading="loading"
                :on-success="picUpload"
                :before-upload="beforeUpload"
                :action='$env.BASE_URL+"/homework/zhty/public/import_file"'
                name="file"
                :headers="{
                  'access-token': $store.state.user.TOKEN,
                }"
                multiple
              >
                <div v-if="!submitForm.jApplication">
                  <i class="el-icon-upload"></i>
                  <div class="el-upload__text">
                    将文件拖到此处，或<em>点击上传</em>
                  </div>
                </div>
                <img
                  style="
                    width: auto;
                    height: auto;
                    max-height: 100%;
                    max-width: 100%;
                  "
                  v-if="submitForm.jApplication"
                  :src="$store.state.user.BASE_URL + submitForm.jApplication"
                  alt=""
                />
                <div class="el-upload__tip" slot="tip">
                  只能上传jpg/png文件，建议大小不超过500kb
                </div>
              </el-upload>
            </el-form-item>
          </div>
        </div>
        <el-form-item label="作业总览"> </el-form-item>
        <div class="showAll">
          <div>
            <span>运动总时长:</span>
            <span>{{ countAllTime }}分钟</span>
          </div>
          <div>
            <span>本周总时长:</span>
            <span>{{ countAllTime }}分钟</span>
          </div>
          <div>
            <span>本周运动项目数:</span>
            <span>{{ countProject }}</span>
          </div>
          <div>
            <span>本周运动项目组数:</span>
            <span>{{ countGroup }}</span>
          </div>
          <div>
            <span>运动器材准备:</span>
            <span>{{...countKitList}}</span>
          </div>
        </div>
        <el-form-item style="margin-top: 10px" label="作业内容"> </el-form-item>
        <div class="showDate">
          <!--        <div @click="changeWeek(index)" v-for="(item,index) in dateWeek" :key="item" :class="checkedDate === index ? 'checkDate':''">-->
          <!--          <span>{{ item }}</span>-->
          <!--        </div>-->
          <el-tabs v-model="checkedDate" @tab-click="changeWeek">
            <el-tab-pane
              v-for="(item, index) in dateWeek"
              :label="item"
              :key="index"
            ></el-tab-pane>
          </el-tabs>
        </div>
        <el-collapse-transition>
          <div
            class="transition-box"
            v-if="index == checkedDate"
            v-for="(item, index) in submitForm.jopList"
          >
            <div>
              <div v-for="(v, k) in item" :key="k" class="project-item">
                <div class="item-top">
                  <span>{{ v.esName }}-{{ countEsTime(v) }}分钟</span>
                  <div v-if="type !== 1" @click="incrementProject(v)">
                    <i class="el-icon-plus"></i>
                    <span>添加项目</span>
                  </div>
                </div>

                <div>
                  <div
                    v-for="(val, key) in v.runIngList"
                    :key="key"
                    class="item-main"
                  >
                    <div class="main-image">
                      <img
                        :src="$store.state.user.BASE_URL + val.peSnapshot"
                        alt=""
                      />
                    </div>
                    <div class="main-right">
                      <div class="main-title">
                        <span>{{ val.peName }}</span>
                      </div>
                      <div class="main-orientation" style="margin-top: 30px">
                        <span>屏幕朝向:</span>
                        <span>{{
                          val.peExecuteDirection == 0 ? "竖屏项目" : "横屏项目"
                        }}</span>
                      </div>
                      <div class="main-orientation">
                        <span>运动强度:</span>
                        <span>{{
                          val.peStrength === 0
                            ? "简单"
                            : val.peStrength === 1
                            ? "中等"
                            : "困难"
                        }}</span>
                      </div>

                      <div class="main-number">
                        <div><span>组数:</span></div>
                        <el-input
                          :disabled="type == 1"
                          @input="isFu(index, k, key)"
                          v-model.number="val.peGroup"
                          size="mini"
                          type="number"
                        ></el-input>
                      </div>
                      <!--              <div class="main-sex">-->
                      <!--                <div>-->
                      <!--                  <span>性别:</span>-->
                      <!--                </div>-->
                      <!--                <el-select size="mini" v-model="value" placeholder="请选择">-->
                      <!--                  <el-option-->
                      <!--                    v-for="item in options"-->
                      <!--                    :key="item.value"-->
                      <!--                    :label="item.label"-->
                      <!--                    :value="item.value">-->
                      <!--                  </el-option>-->
                      <!--                </el-select>-->
                      <!--              </div>-->
                    </div>
                    <div class="main-delete" style="flex: 1">
                      <i
                        v-if="type !== 1"
                        @click="del(index, k, key)"
                        style="color: #f56c6c; float: right; cursor: pointer"
                        class="el-icon-delete"
                      ></i>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </el-collapse-transition>
        <el-form-item>
          <el-button
            size="small"
            :loading="submitLoading"
            v-if="countIF"
            style="float: right; margin-right: 8vw; margin-top: 20px"
            type="primary"
            @click="clickSub(1)"
            >{{type == 0? "添加": type == 2? "修改": type == 3? "另存为": ""}}</el-button
          >
          <el-button
            size="small"
            style="margin-top: 20px; margin-right: 1vw; float: right"
            @click="back"
            >返回</el-button
          >
        </el-form-item>
      </el-form>
      <planAddDialog
        :gradeId="submitForm.jScId"
        @incrementProject="addProject"
        :checkedDate="parseInt(checkedDate)"
        :esId="esId"
        v-if="dialogVisible"
        @close="close"
        :dialog-visible="dialogVisible"
      />
    </div>
  </div>
</template>

<script>
import planAddDialog from "@/views/sports/plan/components/planAddDialog";
import {
  taskStageList,
  saveTaskStage,
  taskStageModelInfo,
  taskStageModelDetail,
  editTaskStage,
  gradelist,
} from "@/api/sports/planAdd";
import debounce from "@/utils/debounce";
import { Message } from "element-ui";
export default {
  name: "planAdd",
  data() {
    return {
      submitForm: {
        jName: "",
        jScId: null,
        jSex: 1,
        jopList: [],
        jApplication: "",
      },
      isLoading: false,
      rules: {
        jName: [{ required: true, message: "请输入计划名称", trigger: "blur" }],
        jScId: [
          { required: true, message: "请选择适用年级", trigger: "change" },
        ],
        jApplication: [{ required: true, message: "请上传计划封面图" }],
      },
      gradeSource: [],
      gradeLoading: false,
      checkedDate: "0",
      dateWeek: ["周一", "周二", "周三", "周四", "周五", "周六", "周日"],
      options: [
        {
          value: 1,
          label: "男",
        },
        {
          value: 2,
          label: "女",
        },
        {
          value: 3,
          label: "全性别",
        },
      ],
      value: "",
      numberValue: 1,
      dialogVisible: false,
      esId: null,
      countKitList: [],
      type: 0,
      loading: false,
      submitLoading: false,
    };
  },
  created() {
    this.getClassSource();
    this.getTaskStageList();
    this.getMessage();
  },
  components: {
    planAddDialog,
  },
  computed: {
    countIF() {
      if (this.type == 1) {
        return false;
      }
      return true;
    },
    countEsTime() {
      return (key) => {
        if (key && key.runIngList) {
          let sumIng = 0;
          key.runIngList.forEach((item) => {
            let time = item.peTime
              ? parseInt(item.peTime) * parseInt(item.peGroup)
              : 0;
            sumIng += time;
          });
          return (sumIng / 60).toFixed(1) == 0.0 ? 0 : (sumIng / 60).toFixed(1);
        } else {
          return 0;
        }
      };
    },
    countAllTime() {
      let sumIng = 0;
      if (this.submitForm && this.submitForm.jopList.length) {
        this.submitForm.jopList.forEach((item) => {
          if (item) {
            item.forEach((val) => {
              val.runIngList.forEach((v) => {
                let time = v.peTime
                  ? parseInt(v.peTime) * parseInt(v.peGroup)
                  : 0;
                sumIng += time;
              });
            });
          }
        });
        return (sumIng / 60).toFixed(1) == 0.0 ? 0 : (sumIng / 60).toFixed(1);
      } else {
        return 0;
      }
    },
    countProject() {
      let sumIng = 0;
      this.submitForm.jopList.forEach((item) => {
        if (item) {
          item.forEach((val) => {
            sumIng += val.runIngList.length;
          });
        }
      });
      return sumIng ? sumIng : 0;
    },
    countGroup() {
      let sumIng = 0;
      if (this.submitForm.jopList.length) {
        this.submitForm.jopList.forEach((item) => {
          if (item) {
            item.forEach((val) => {
              val.runIngList.forEach((v) => {
                let countAll = v.peGroup ? parseInt(v.peGroup) : 0;
                sumIng += countAll;
              });
            });
          }
        });
      }
      return sumIng;
    },
  },
  methods: {
    goBack() {
      this.$router.back();
    },
    clickMessage: debounce((e) => {
      Message.error(e);
    }, 500),
    clickSub: debounce(function (type) {
      if (type) {
        this.onSubmit();
      } else {
        this.onSub();
      }
    }),
    picUpload(e) {
      if (e.code === 200) {
        this.submitForm.jApplication = e.result.pic;
      } else if (e.code === 401) {
        this.$router.replace("/");
        this.$message.error("您的身份信息已过期，请重新登录");
        sessionStorage.removeItem("userInfo");
        sessionStorage.removeItem("token");
        this.$store.commit("user/SET_TOKEN", "");
      } else {
        this.$message.error(e.message);
      }
      this.loading = false;
    },
    beforeUpload(file) {
      this.loading = true;
      const fileSuffix = file.name.substring(file.name.lastIndexOf(".") + 1);
      const types = ["jpeg", "jpg", "png"];
      if (!types.includes(fileSuffix)) {
        this.$message.error(`文件只能是 ${types.join()} 格式!`);
        this.loading = false;
      }
      return types.includes(fileSuffix);
    },
    del(index, k, key) {
      this.$confirm("此操作将永久删除该作业, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.submitForm.jopList[index][k].runIngList.splice([key], 1);
          this.countQiCai();
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    countQiCai() {
      this.countKitList = [];
      this.submitForm.jopList.forEach((item) => {
        if (item) {
          item.forEach((v) => {
            v.runIngList.forEach((val) => {
              if (val.peEquipment !== "无") {
                this.countKitList.push(val.peEquipment);
                this.countKitList = [...new Set(this.countKitList)];
              }
            });
          });
        }
      });
    },
    back() {
      this.$router.back();
    },
    getMessage() {
      if (this.$route.query.type) {
        this.type = this.$route.query.type;
      }
      if (this.$route.query.id) {
        this.loading = true;
        if (this.type == 1) {
          taskStageModelDetail({
            jId: this.$route.query.id,
            jeAuthor:this.$store.state.user.USER_INFO.pscShId
          }).then(
            (response) => {
              if (response.code === 200) {
                this.submitForm.jName = response.result.jName;
                this.submitForm.jSex = parseInt(response.result.jSex);
                this.submitForm.jScId = response.result.jScId;
                this.submitForm.jApplication = response.result.jApplication;
                this.submitForm.jopList = response.result.cycleVo
                  .map((item) => [...item.codeVO])
                  .map((v, index) =>
                    [...v].map((val) => ({
                      ...val,
                      runIngList: val.runIngList.map((value) => ({
                        ...value,
                        peGroup: value.jopPeGroup,
                        checkedDate: index + 1,
                      })),
                    }))
                  );
                this.countQiCai();
                this.loading = false;
              }
            }
          );
        } else {
          taskStageModelInfo({
            jId: this.$route.query.id,
            jeSource: this.$route.query.jSource,
            jeAuthor:this.$store.state.user.USER_INFO.pscShId
          }).then((response) => {
            if (response.code === 200) {
              this.submitForm.jName = response.result.jName;
              this.submitForm.jSex = parseInt(response.result.jSex);
              if (this.gradeSource.length) {
                if (this.gradeSource.some((item) => item.scId === response.result.jScId)) {
                  this.submitForm.jScId = response.result.jScId;
                }
              }
              this.submitForm.jApplication = response.result.jApplication;
              this.submitForm.jopList = response.result.cycleVo
                .map((item) => [...item.codeVO])
                .map((v, index) =>
                  [...v].map((val) => ({
                    ...val,
                    runIngList: val.runIngList.map((value) => ({
                      ...value,
                      peGroup: value.jopPeGroup,
                      checkedDate: index + 1,
                    })),
                  }))
                );
              this.countQiCai();
              this.loading = false;
            }
          });
        }
      }
    },
    onSubmit() {
      this.$refs.submitForm.validate((val) => {
        if (val) {
          this.submitLoading = true;
          let addData = [];
          this.submitForm.jopList.forEach((item) => {
            item.forEach((v) => {
              addData.push(v.runIngList);
            });
          });
          let incrementSource = [];
          for (let i = 1; i < 8; i++) {
            addData.forEach((item) => {
              let res = item.filter((item) => parseInt(item.checkedDate) === i);

              res.forEach((item) => {
                incrementSource.push(item);
              });
            });
          }
          let incrementData = [];
          for (let i = 1; i < 8; i++) {
            let res = incrementSource.filter(
              (item) => parseInt(item.checkedDate) === i
            );
            incrementData.push(res);
          }
          let addSource = [];
          incrementData.forEach((item, index) => {
            addSource.push({
              eCycle: index + 1,
              peCode: item.map((val) => val.peCode),
              peGroup: item.map((val) => val.peGroup),
            });
          });
          const {submitForm} = this;
          if (this.type == 2) {
            editTaskStage({
              ...this.submitForm,
              jApplication: this.submitForm.jApplication
                ? this.submitForm.jApplication
                : "/2022/mould/默认.jpg",
              jopList: addSource,
              jScId:submitForm.jScId,
              jEAuthor: this.$store.state.user.USER_INFO.id,
              jShId: this.$store.state.user.USER_INFO.pscShId,
              jId: this.$route.query.id,
            }).then((response) => {
              this.submitLoading = false;
              if (response.code === 200) {
                this.$message.success("修改成功");
                this.$router.push("/sports/Aplan");
                this.submitLoading = false;
              } else {
                this.$message.error(response.message);
              }
            });
          } else {
            saveTaskStage({
              ...this.submitForm,
              jApplication: this.submitForm.jApplication
                ? this.submitForm.jApplication
                : "/2022/mould/默认.jpg",
              jopList: addSource,
              jScId:submitForm.jScId,
              jEAuthor: this.$store.state.user.USER_INFO.id,
              jShId: this.$store.state.user.USER_INFO.pscShId,
            }).then((response) => {
              if (response.code === 200) {
                this.submitLoading = false;
                // this.$message.success("布置成功，您当前布置的计划会在下周开始实施，本周作业计划不变");
                this.$router.push("/sports/Aplan");
                this.submitLoading = false;
              } else {
                this.$message.error(response.message);
              }
            });
          }
        } else {
          return false;
        }
      });
    },
    onSub() {
      this.$refs.submitForm.validate((val) => {
        if (val) {
          this.submitLoading = true;
          let addData = [];
          this.submitForm.jopList.forEach((item) => {
            item.forEach((v) => {
              addData.push(v.runIngList);
            });
          });
          let incrementSource = [];
          for (let i = 1; i < 8; i++) {
            addData.forEach((item) => {
              let res = item.filter((item) => parseInt(item.checkedDate) === i);
              res.forEach((item) => {
                incrementSource.push(item);
              });
            });
          }
          let incrementData = [];
          for (let i = 1; i < 8; i++) {
            let res = incrementSource.filter(
              (item) => parseInt(item.checkedDate) === i
            );
            incrementData.push(res);
          }
          let addSource = [];
          incrementData.forEach((item, index) => {
            addSource.push({
              eCycle: index + 1,
              peCode: item.map((val) => val.peCode),
              peGroup: item.map((val) => val.peGroup),
            });
          });
          saveTaskStage({
            ...this.submitForm,
            jopList: addSource,
            jEAuthor: this.$store.state.user.USER_INFO.id,
            jShId: this.$store.state.user.USER_INFO.pscShId,
          }).then((response) => {
            this.submitLoading = false;
            if (response.code === 200) {
              this.$router.push("/sports/Aplan");
              this.$message.success("添加成功");
            } else {
              this.$message.error(response.message);
            }
          });
        } else {
          return false;
        }
      });
    },
    getClassSource() {
      this.gradeLoading = true;
      gradelist({
        teacherId: this.$store.state.user.USER_INFO.id,
      }).then((response) => {
        if (response.code === 200) {
          this.gradeSource = response.result;
        }
        this.gradeLoading = false;
      });
    },
    changeWeek(tab, event) {
      this.checkedDate = tab.index;
      // this.checkedDate = index
    },
    isFu(index, k, key) {
      if (this.submitForm.jopList[index][k].runIngList[key].peGroup < 1) {
        this.submitForm.jopList[index][k].runIngList[key].peGroup = 1;
        this.clickMessage("最少一组哦");
      }
      if (this.submitForm.jopList[index][k].runIngList[key].peGroup > 99) {
        this.submitForm.jopList[index][k].runIngList[key].peGroup = 99;
        this.clickMessage("让学生轻松点吧");
      }
    },
    close() {
      this.dialogVisible = false;
    },
    getTaskStageList() {
      taskStageList().then((response) => {
        if (response.code === 200) {
          let res = response.result.map((item) => ({
            ...item,
            runIngList: [],
          }));
          for (let i = 0; i < 7; i++) {
            this.submitForm.jopList.push(res);
          }
        }
      });
    },
    incrementProject(data) {
      this.dialogVisible = true;
      this.esId = data.esId;
    },
    addProject(project) {
      const index = this.submitForm.jopList[0].findIndex(
        (item) => item.esId === this.esId
      );
      let arr = JSON.parse(JSON.stringify(this.submitForm.jopList));
      if (
        arr[parseInt(this.checkedDate)][index].runIngList.filter(
          (item) => item.peCode == project.peCode
        ).length
      ) {
        let ids = arr[parseInt(this.checkedDate)][index].runIngList.findIndex(
          (item) => item.peCode == project.peCode
        );
        arr[parseInt(this.checkedDate)][index].runIngList[ids].peGroup =
          arr[parseInt(this.checkedDate)][index].runIngList[ids].peGroup +
          project.peGroup;
      } else {
        arr[parseInt(this.checkedDate)][index].runIngList.push(project);
      }
      this.submitForm.jopList = arr;
      if (this.submitForm.jopList.length) {
        this.countQiCai();
      }
      this.close();
    },
  },
};
</script>

<style lang="scss" scoped>
.commonForm {
  ::v-deep .el-form-item__label {
    color: #4f4f4f;
    font-size: 12px;
    font-weight: 400;
  }
}
.showAll {
  width: 65vw;
  background: #eff7ff;
  height: 50px;
  margin-left: 130px;
  display: flex;
  align-items: center;
  margin-top: -20px;
  div {
    margin-left: 10px;
    color: #1890ff;
    span {
      font-size: 12px;
      margin-left: 3px;
    }
  }
}
.showDate {
  height: 50px;
  width: 65vw;
  display: flex;
  margin-left: 130px;
  margin-top: -22px;
  align-items: center;
  padding-left: 3px;
  box-sizing: border-box;
  div {
    margin-right: 35px;
    font-size: 14px;
    cursor: pointer;
    &.checkDate {
      color: #1890ff;
      box-sizing: border-box;
      position: relative;
      &::before {
        content: "";
        width: 100%;
        height: 3px;
        background: #1890ff;
        position: absolute;
        bottom: -4px;
      }
    }
  }
}
.project-item {
  margin-left: 130px;
  .item-top {
    width: 65vw;
    height: 40px;
    background: #f6f8f9;
    display: flex;
    align-items: center;
    justify-content: center;
    position: relative;
    span {
      font-size: 14px;
    }
    div {
      cursor: pointer;
      position: absolute;
      right: 40px;
      color: #1890ff;
      span {
        font-size: 12px;
      }
      i {
        margin-right: 5px;
        &:before {
          font-size: 12px;
        }
      }
    }
  }
  .item-main {
    width: 800px;
    height: 200px;
    padding: 12px 0;
    box-sizing: border-box;
    display: flex;
    .main-image {
      width: 300px;
      display: flex;
      justify-content: center;
      img {
        max-width: 100%;
        max-height: 100%;
        height: auto;
        width: auto;
        border-radius: 4px;
      }
    }
    .main-right {
      display: flex;
      flex-direction: column;
      padding-left: 25px;
      .main-title {
        color: #3d3d3d;
        font-size: 14px;
      }
      .main-orientation {
        color: #878787;
        font-size: 12px;
        margin-top: 5px;

        span {
          &:last-child {
            margin-left: 5px;
          }
        }
      }
      .main-number {
        color: #3d3d3d;
        display: flex;
        font-size: 14px;
        margin-top: 23px;
        align-items: center;
        ::v-deep .el-input {
          width: 80px;
          margin-left: 20px;
          ::v-deep .el-input__inner {
            height: 10px;
          }
        }
      }
      .main-sex {
        color: #4f4f4f;
        display: flex;
        font-size: 14px;
        margin-top: 20px;
        align-items: center;
        ::v-deep .el-select {
          width: 100px;
          margin-left: 20px;
        }
      }
    }
  }
}
::v-deep .el-upload-list__item {
  display: none;
}
</style>
